/*******************************************************************************************
Copyright (C) 2016 Mestrelab Research S.L. All rights reserved.

This file is part of the Mnova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*******************************************************************************************/

/*globals Action, Application, MessageBox, FileDialog, mnDebug,
 Settings, mnError, Dir, CSPResult, File, TextStream, FileLineEdit, CommonSlots,
 mainWindow, Document, serialization, nmr, qsTr, FileInfo, print, NMRProcessing,
 NMRSpectrum, MnUi, TCSPSettingsHandler*/
/*jslint plusplus: true, indent: 4, white: true, continue: true*/

function ImportCSPHandler(aTitrationFile, aLigandFile, aPeaksFile, aBaseDir, aReportPath, closeDocs) {
	"use strict";

	this.fUnits = "";
	this.fPt = 0;
	this.fRefLt = {}; //(expno, lt)
	this.fLtMap = {}; //map of arrays (L1, [(expno, lt)])
	this.fLtAbsolute = true;
	this.fLigandsMap = {}; //map (L, "annotation")
	this.fTitrationFilePath = aTitrationFile || "";
	this.fLigandFilePath = aLigandFile || "";
	this.fPeaksFilePath = aPeaksFile || "";
	this.fPeakList = [];
	this.fBaseDir = aBaseDir || "";
	this.fShowSeries = ImportCSPHandler.settingsObject().value("/ShowSeries", false);
	this.fSettings = { fShowSeries: false, fImportMask: "ser" };
	this.fReportPath = aReportPath || "";
	this.fProcTemplate = undefined;
	this.closeDocs = closeDocs;

	this.init();
}

ImportCSPHandler.readLine = function (aStrm) {
	"use strict";

	var line = aStrm.readLine().trimmed();
	line = line.replace(/\s+/g, " ");
	return line;
};

ImportCSPHandler.importSettingsPrivate = undefined;
ImportCSPHandler.settingsObject = function () {
	'use strict';

	if (ImportCSPHandler.importSettingsPrivate === undefined) {
		ImportCSPHandler.importSettingsPrivate = new Settings("/ImportCSP/");
	}
	return ImportCSPHandler.importSettingsPrivate;
};

ImportCSPHandler.defaultDirectory = function() {
	'use strict';
	return ImportCSPHandler.settingsObject().value("/DefaultDir", Dir.home());
};

ImportCSPHandler.setDefaultDirectory = function(aDefDir) {
	'use strict';
	ImportCSPHandler.settingsObject().setValue("/DefaultDir", aDefDir);
};

ImportCSPHandler.importPeakListFromFile = function() {
	'use strict';
	var wd = ImportCSPHandler.settingsObject().value("PeaksFile", Dir.home()),
		currentResult = new CSPResult(Application.binding.currentResultId),
		pListPath;
	if (!currentResult.isValid()) {
		mnError("Invalid result %1".arg(Application.binding.currentResultId));
		MessageBox.critical("Invalid result");
		return;
	}
	mnDebug("Current result %1".arg(currentResult.uuid));
	pListPath = FileDialog.getOpenFileName("Peak list (*.txt)", "Select peak list", wd);
	if (pListPath) {
		mnDebug("Peak list path %1".arg(pListPath));
		ImportCSPHandler.settingsObject().setValue("PeaksFile", pListPath);
		ImportCSPHandler.importPeakList(currentResult, pListPath);
	}
};

ImportCSPHandler.staticParsePeakList = function(aFilePath) {
	'use strict';

	var file = new File(aFilePath),
		txtStrm, peakArr = [], line, lineArr, w1, w2, label;

	if (file.open(File.ReadOnly)) {
		txtStrm = new TextStream(file);
		while (!txtStrm.atEnd()) {
			line = ImportCSPHandler.readLine(txtStrm);
			if (!line.isEmpty()) {
				lineArr = line.split(" ");
				label = lineArr[0];
				w1 = parseFloat(lineArr[1]);
				w2 = parseFloat(lineArr[2]);
				if (!isNaN(w1)) {
					if (!isNaN(w2)) {
						mnDebug("Adding [%1, %2] %3".arg(w2).arg(w1).arg(label));
						//aCSPResult.addPeakSerie({x: w2, y: w1, annotation: label});
						peakArr.push({x: w2, y: w1, annotation: label});
					} else {
						mnDebug("Adding [%1] %3".arg(w1).arg(label));
						//aCSPResult.addPeakSerie({x: w2, y: w1, annotation: label});
						peakArr.push({x: w1, annotation: label});
					}

				}
			}
		}
	}
	return peakArr;
};

ImportCSPHandler.importPeakList = function(aCSPResult, aFilePath) {
	'use strict';
	var peakArr = ImportCSPHandler.staticParsePeakList(aFilePath),
		i = 0;

	if (peakArr) {
		Application.mainWindow.setBusy(qsTr("Importing Peaks"));
		Application.mainWindow.processEvents();
		for (i = 0; i < peakArr.length; ++i) {
			aCSPResult.addPeakSerie(peakArr[i]);
		}
		Application.mainWindow.endBusy();
	}
};

ImportCSPHandler.isValidInput = function() {
	"use strict";

	this.widgets.fOkPushButton.enabled = this.widgets.fTitrationsLineEdit.text && this.widgets.fBaseDirLineEdit.text;

};

ImportCSPHandler.onOpenFile = function () {
	"use strict";
	var fileName = this.text || ImportCSPHandler.defaultDirectory(),
		fi;

	fileName = FileDialog.getOpenFileName(this.filter || "", qsTr("Open File"), (fileName || Dir.home()));
	if (fileName) {
		mnDebug(fileName);
		fi = new FileInfo(fileName);
		mnDebug(fi.dir.absPath);
		// ImportCSPHandler.setDefaultDirectory(fi.dir.absPath);
		this.text = fileName;
	}
};

ImportCSPHandler.onSaveFile = function() {
	"use strict";
	var fileName = this.text || ImportCSPHandler.defaultDirectory(),
		fi;

	fileName = FileDialog.getSaveFileName(this.filter || "", qsTr("Save File"), (fileName || Dir.home()));
	if (fileName) {
		fi = new FileInfo(fileName);
		mnDebug(fi.dir.absPath);
		// ImportCSPHandler.setDefaultDirectory(fi.dir.absPath);
		this.text = fileName;
	}
};

ImportCSPHandler.onOpenDir = function () {
	"use strict";
	var dirName = this.text || ImportCSPHandler.defaultDirectory(),
		fi;

	dirName = FileDialog.getExistingDirectory(dirName);
	if (dirName) {
		fi = new FileInfo(dirName);
		ImportCSPHandler.setDefaultDirectory(fi.absoluteFilePath);
		this.text = dirName;
	}
};

ImportCSPHandler.onCSPOpenTriggered = function() {
	'use strict';
	var diag = Application.loadUiFile("ricares:WImportCSPDialog.ui"),
		directoryLineEdit = new FileLineEdit(
			diag.widgets.fBaseDirLineEdit, diag.widgets.fBaseDirToolButton,
			undefined, undefined, undefined,
			ImportCSPHandler.onOpenDir, diag.accepted),
		titrationLineEdit = new FileLineEdit(
			diag.widgets.fTitrationsLineEdit, diag.widgets.fTitrationsToolButton,
			"Titration files (*.txt)", undefined, undefined,
			ImportCSPHandler.onOpenFile, diag.accepted),
		ligandsLineEdit = new FileLineEdit(
			diag.widgets.fLigandsLineEdit, diag.widgets.fLigandsToolButton,
			"Ligands files (*.txt)", undefined, undefined,
			ImportCSPHandler.onOpenFile, diag.accepted),
		peaksLineEdit = new FileLineEdit(
			diag.widgets.fPeaksLineEdit, diag.widgets.fPeaksToolButton,
			"Peaks files (*.txt)", undefined, undefined,
			ImportCSPHandler.onOpenFile, diag.accepted),
		reportLineEdit = new FileLineEdit(
			diag.widgets.fReportLineEdit, diag.widgets.fReportToolButton,
			undefined, undefined, undefined,
			ImportCSPHandler.onSaveFile, diag.accepted),
		procTemplateLineEdit = new FileLineEdit(
			diag.widgets.fProcTemplateLineEdit, diag.widgets.fProcTemplateToolButton,
			"Processing Templates (*.mnp)", undefined, undefined,
			ImportCSPHandler.onOpenFile, diag.accepted),
		ckCloseDocs = diag.widgets.ckCloseDocs,
		cspHandler = new ImportCSPHandler(titrationLineEdit.fText, ligandsLineEdit.fText, peaksLineEdit.fText, directoryLineEdit.fText, reportLineEdit.fText, ckCloseDocs.checked);

	diag.widgets.fTitrationsLineEdit.textChanged.connect(cspHandler, "setTitrationFilePath");
	diag.widgets.fTitrationsLineEdit.textChanged.connect(diag, ImportCSPHandler.isValidInput);
	diag.widgets.fLigandsLineEdit.textChanged.connect(cspHandler, "setLigandFilePath");
	diag.widgets.fLigandsLineEdit.textChanged.connect(diag, ImportCSPHandler.isValidInput);
	diag.widgets.fPeaksLineEdit.textChanged.connect(cspHandler, "setPeakFilePath");
	diag.widgets.fPeaksLineEdit.textChanged.connect(diag, ImportCSPHandler.isValidInput);
	diag.widgets.fBaseDirLineEdit.textChanged.connect(cspHandler, "setBaseDir");
	diag.widgets.fBaseDirLineEdit.textChanged.connect(diag, ImportCSPHandler.isValidInput);
	diag.widgets.fReportLineEdit.textChanged.connect(cspHandler, "setReportFile");
	diag.widgets.fProcTemplateLineEdit.textChanged.connect(cspHandler, "setProcessingTemplate");
	diag.widgets.ckCloseDocs.toggled.connect(cspHandler, function(checked) {
		this.closeDocs = checked;
	});
	diag.widgets.fSettingsPushButton.clicked.connect(cspHandler.fSettings, function() {
		var prefUi = Application.loadUiFile("ricares:WImportCSPSettingsDialog.ui"),
			thisSettings = new TCSPSettingsHandler("ImportCSP", {"masks": ["ser", "pdata/*/2rr", "fid"]}),
			defMasks = thisSettings.masks,
			indOf = defMasks.indexOf(this.fImportMask);
		if (indOf < 0) {
			indOf = defMasks.length;
			defMasks.push(this.fImportMask);
		}
		prefUi.widgets.fInputMaskComboBox.items = defMasks;
		prefUi.widgets.fShowSeriesCheckBox.checked = this.fShowSeries;
		prefUi.widgets.fInputMaskComboBox.currentIndex = indOf;
		if (prefUi.exec()) {
			this.fShowSeries = prefUi.widgets.fShowSeriesCheckBox.checked;
			this.fImportMask = prefUi.widgets.fInputMaskComboBox.currentText;
			if (defMasks.indexOf(this.fImportMask) < 0) {
				defMasks.push(this.fImportMask);
			}
			thisSettings.masks = defMasks;
		}
	});
	diag.accepted.connect(cspHandler, "onAccepted");
	ImportCSPHandler.isValidInput.call(diag);
	diag.exec();
};

ImportCSPHandler.prototype = {
	init: function() {
		'use strict';

		this.readSettings();

		this.parseTitrationFile();
		this.parseLigandFile();
		this.parsePeakFile();
	},

	readSettings: function() {
		'use strict';

		var savedSetts = JSON.parse(ImportCSPHandler.settingsObject().value("/Settings", JSON.stringify(this.fSettings))),
			v;
		for (v in savedSetts) {
			if (savedSetts.hasOwnProperty(v)) {
				if (this.fSettings.hasOwnProperty(v)) {
					this.fSettings[v] = savedSetts[v];
				} else if (v === "fImport2rr" && savedSetts.fImport2rr && this.fSettings.fImportMask !== "pdata/*/2rr") {
					this.fSettings.fImportMask = "pdata/*/2rr";
				}
			}
		}
	},

	saveSettings: function() {
		'use strict';

		ImportCSPHandler.settingsObject().setValue("/Settings", JSON.stringify(this.fSettings));
	},

	parseTitrationFile: function() {
		"use strict";

		if (!this.fTitrationFilePath) {
			return;
		}

		var file = new File(this.fTitrationFilePath),
			proteinRE = /^\[Pt?\]([a-zA-Z]+)\s(\d+(?:\.\d+)?)$/,//
			expnoRE = /^EXPNO\s+(\S+)$/i,
			ligandRE = /^(L\d+)$/,
			relativeRE = /\[Lt?\]\/\[Pt?\]/,
			match, strm, line, arr, skipRead = false;

		mnDebug("Parsing titration file");

		this.fUnits = "";
		this.fPt = 0;
		this.fRefLt = {}; //(expno, lt)
		this.fLtMap = {}; //map of arrays (L1, [(expno, lt)])

		if (!file) {
			return;
		}

		if (file.open(File.ReadOnly)) {
			strm = new TextStream(file);
			 while (!strm.atEnd()) {
				if (!skipRead) {
					line = ImportCSPHandler.readLine(strm);
				}
				skipRead = false;
				if (!line.isEmpty()) {
					if (expnoRE.test(line)) {
						match = line.match(expnoRE);
						mnDebug("EXPNO %1".arg(match[1]));
						if (relativeRE.test(match[1])) {
							mnDebug("Relative Lt");
							this.fLtAbsolute = false;
						}
					} else if (/^REF$/i.test(line)) {
						line = ImportCSPHandler.readLine(strm);
						arr = line.split(" ");
						this.fRefLt.expno = arr[0];
						this.fRefLt.lt = parseFloat(arr[1]);
						mnDebug("Ref expno: %1, Lt: %2".arg(this.fRefLt.expno).arg(this.fRefLt.lt));
					} else if (ligandRE.test(line)) { //begin of ligand, starts with L?
						match = line.match(ligandRE);
						this.fLtMap[match[1]] = [];
						while (!skipRead && !strm.atEnd()) {
							line = ImportCSPHandler.readLine(strm);//read all lines until empty line as expno,lt
							skipRead = ligandRE.test(line);
							if (line && !skipRead) {
								arr = line.split(" ");
								this.fLtMap[match[1]].push({"expno": arr[0], "lt": parseFloat(arr[1])});
								mnDebug("%1: expno %2, Lt: %3".arg(match[1]).arg(arr[0]).arg(parseFloat(arr[1])));
							}
						}
					} else if (proteinRE.test(line)) {
						match = line.match(proteinRE);
						this.fUnits = match[1];
						this.fPt = parseFloat(match[2]);
						mnDebug("Pt: %1, Units: %2".arg(this.fPt).arg(this.fUnits));
					}
				}
			}
		} else {
			mnDebug("Unable to open %1".arg(this.fTitrationFilePath));
		}

		if (this.fPt === 0) {
			throw "Pt not detected";
		}
	},

	setTitrationFilePath: function(aTitrationFilePath) {
		"use strict";

		mnDebug("setTitrationFilePath %1".arg(aTitrationFilePath));
		if (aTitrationFilePath !== this.fTitrationFilePath) {
			this.fTitrationFilePath = aTitrationFilePath;
			this.parseTitrationFile();
		}
	},

	parseLigandFile: function() {
		'use strict';

		if (!this.fLigandFilePath) {
			return;
		}

		var file = new File(this.fLigandFilePath),
			txtStrm, arr, line;

		mnDebug("Parsing ligand file");
		this.fLigandsMap = {};
		if (file.open(File.ReadOnly)) {
			txtStrm = new TextStream(file);
			while (!txtStrm.atEnd()) {
				line = ImportCSPHandler.readLine(txtStrm);
				if (line) {
					arr = line.split(" ");
					this.fLigandsMap[arr[0]] = arr.slice(1).join(" ");
					mnDebug("%1: %2".arg(arr[0]).arg(this.fLigandsMap[arr[0]]));
				}
			}
		} else {
			mnDebug("Unable to open %1".arg(this.fLigandFilePath));
		}
	},

	setLigandFilePath: function(aLigandFilePath) {
		"use strict";

		mnDebug("setLigandFilePath %1 %2".arg(aLigandFilePath).arg(this.fLigandFilePath));
		if (aLigandFilePath !== this.fLigandFilePath) {
			this.fLigandFilePath = aLigandFilePath;
			this.parseLigandFile();
		}
	},

	parsePeakFile: function() {
		"use strict";

		if (!this.fPeaksFilePath) {
			return;
		}

		mnDebug("Parsing peaks file");
		this.fPeakList = ImportCSPHandler.staticParsePeakList(this.fPeaksFilePath);
	},

	setPeakFilePath: function(aPeakFilePath) {
		"use strict";

		if (aPeakFilePath !== this.fPeaksFilePath) {
			this.fPeaksFilePath = aPeakFilePath;
			this.parsePeakFile();
		}
	},

	setReportFile: function(aReportPath) {
		"use strict";

		if (aReportPath !== this.fReportPath) {
			this.fReportPath = aReportPath;
		}
	},

	setProcessingTemplate: function(aProcTemplate) {
		"use strict";

		if (aProcTemplate !== this.fProcTemplate) {
			this.fProcTemplate = aProcTemplate;
		}
	},

	setBaseDir: function(aBaseDir) {
		"use strict";

		if (aBaseDir !== this.fBaseDir) {
			this.fBaseDir = aBaseDir;
		}
	},

	sortDataByKdIndex : function (aDataArray, aKdIndex) {
		"use strict";

		var aCopy = JSON.parse(JSON.stringify(aDataArray));

		function compare (a, b) {
			return a.kds[aKdIndex].kd - b.kds[aKdIndex].kd;
		}
		return aCopy.sort(compare);
	},

	onAccepted: function() {
		"use strict";

		var prop, i, ligandName, j, auxFile, csvReportFile, outputDir, sortedOpenedData,
			ligandDesc, doc, refPath, getPathFunc, serArr, path, nmrItems, arrItem, cspResult, kdMethods,
			cspProps, ltArr, cspSetts, baseDir, fi, openedData = [], docPath, reportFile, reportStrm,
			methodResult, proc, nmrSpc,
			kdMethodsTemplate = [ {"method": CSPResult.AutoAll, "factor": 0, "label": "All"},
									{"method": CSPResult.AutoMean, "factor": 0, "label": "mean_0s"},
									{"method": CSPResult.AutoMean, "factor": 1, "label": "mean_1s"},
									{"method": CSPResult.AutoMean, "factor": 2, "label": "mean_2s"},
									{"method": CSPResult.AutoMedian, "factor": CSPResult.Q1, "label": "median>Q1"},
									{"method": CSPResult.AutoMedian, "factor": CSPResult.Q2, "label": "median>Q2"},
									{"method": CSPResult.AutoMedian, "factor": CSPResult.Q3, "label": "median>Q3"}];

		getPathFunc = function(aExpNo) {
			var dirName = "%1/%2/".arg(this.fBaseDir).arg(aExpNo),
				dataDir, filesArr;
			dataDir = new Dir(dirName);
			if (dataDir.exists) {
				filesArr = dataDir.entryListAdv(this.fSettings.fImportMask);
				mnDebug("Files: %1".arg(filesArr));
				return filesArr[0];
			}
			return undefined;
		};

		mnDebug("CSP accepted");

		this.saveSettings();

		refPath = getPathFunc.call(this, this.fRefLt.expno);
		for (prop in this.fLtMap) {
			if (this.fLtMap.hasOwnProperty(prop)) {
				doc = new Document();
				Application.lockDocument(doc);
				serArr = [refPath];
				ltArr = [this.fRefLt.lt];

				ligandDesc = this.fLtMap[prop];
				if (this.fLigandsMap[prop]) {
					ligandName = this.fLigandsMap[prop];
				} else {
					ligandName = prop;
				}
				mnDebug("%1 %2: %3".arg(ligandName).arg(refPath).arg(this.fRefLt.lt));
				for (i = 0; i < ligandDesc.length; ++i) {
					path = getPathFunc.call(this, ligandDesc[i].expno);
					if (path) {
						serArr.push(path);
						ltArr.push(ligandDesc[i].lt);
						mnDebug("%1 %2: %3".arg(ligandName).arg(path).arg(ligandDesc[i].lt));
					} else {
						mnError("No path found for %1".arg(ligandName));
					}
				}

				if (serArr.length === 1) {
					mnError("No paths found for %1".arg(ligandName));
					Application.unlockDocument();
					continue;
				}

				serialization.open(serArr);
				nmrItems = doc.itemsByName('NMR Spectrum');
				if (nmrItems.length !== serArr.length) {
					MessageBox.critical("Unable to open all the spectra");
					Application.unlockDocument();
					return;
				}

				if (this.fProcTemplate) {
					for (i = 0; i < nmrItems.length; ++i) {
						mnDebug("Applying processing template");
						nmrSpc = new NMRSpectrum(nmrItems[i]);
						proc = new NMRProcessing(this.fProcTemplate);
						nmrSpc.proc = proc;
						nmrSpc.process();
					}
				}

				arrItem = nmr.createArrayedItem(nmrItems, false);
				arrItem.setProperty("stacked.2dcolor.type", "Hue");
				for(i = 0; i < nmrItems.length; ++i) {
					doc.deletePages([nmrItems[i].page]);
				}

				try {
					cspResult = new CSPResult(arrItem);
				} catch(er) {
					MessageBox.critical(
						"Unable to create CSP experiment:\n%1".arg(er));
				}

				cspSetts = cspResult.settings;
				cspSetts.units = this.fUnits;
				cspResult.settings = cspSetts;
				cspResult.title = ligandName;
				cspProps = cspResult.reactionProperties;
				for (i = 0; i < ltArr.length; ++i) {
					cspProps[i] = { pt: this.fPt };
					if (this.fLtAbsolute) {
						cspProps[i].lt = ltArr[i];
					} else {
						cspProps[i].ltPt = ltArr[i];
					}
				}
				cspResult.reactionProperties = cspProps;

				for (i = 0; i < this.fPeakList.length; ++i) {
					cspResult.addPeakSerie(this.fPeakList[i], this.fSettings.fShowSeries);
				}

				kdMethods = JSON.parse(JSON.stringify(kdMethodsTemplate));
				for (i = 0; i < kdMethods.length; ++i) {
					methodResult = kdMethods[i];
					cspResult.recalculateKd(methodResult.method, methodResult.factor);
					methodResult.kd = cspResult.kd;
					methodResult.kdStdDev = cspResult.kdStdDev;
					kdMethods[i] = methodResult;
				}
				cspResult.recalculateKd(CSPResult.AutoAll, 0);

				fi = new FileInfo(this.fTitrationFilePath);
				baseDir = fi.dir.absPath;
				docPath = "%1/%2.mnova".arg(baseDir).arg(ligandName.replace(/\s+/, "_"));
				serialization.save(docPath, "mnova");

				openedData.push({
					"docPath": docPath,
					"ligand": prop,
					"ligandName": ligandName,
					"cspResult": cspResult,
					"kds": kdMethods
				});

				Application.unlockDocument();
				Application.mainWindow.addDocument(doc);
				if (this.closeDocs) {
					doc.close();
				}
			}
		}

		if (openedData.length && this.fReportPath) {
			reportFile = new File(this.fReportPath);
			if (reportFile.open(File.WriteOnly)) {
				reportStrm = new TextStream(reportFile);
				arrItem = ["L", "Ligand", "File"];
				for (i = 0; i < openedData[0].kds.length; ++i) {
					arrItem.push(openedData[0].kds[i].label);
					arrItem.push("Error");
				}
				reportStrm.writeln(arrItem.join(","));
				for (i = 0; i < openedData.length; ++i) {
					prop = openedData[i];
					arrItem = [prop.ligand, prop.ligandName, prop.docPath];
					for (j = 0; j < prop.kds.length; ++j) {
						arrItem.push(prop.kds[j].kd);
						arrItem.push(prop.kds[j].kdStdDev);
					}
					reportStrm.writeln(arrItem.join(","));
				}
				reportFile.close();
			} else {
				mnError("Unable to open file %1".arg(this.fReportPath));
			}
		}

		if (openedData.length && this.fReportPath) {
			auxFile = new File(this.fReportPath);
			outputDir = new Dir(auxFile.absDirPath);
			csvReportFile = new File(outputDir.filePath("mnova_CSP.csv"));
			if (csvReportFile.open(File.WriteOnly)) {
				reportStrm = new TextStream(csvReportFile);
				arrItem = ["L", "LIGAND", "FILE", "KD", "SD"];
				reportStrm.writeln(arrItem.join(",")); //
				sortedOpenedData = this.sortDataByKdIndex(openedData, 4);

				for (i = 0; i < sortedOpenedData.length; ++i) {
					prop = sortedOpenedData[i];
					arrItem = [prop.ligand, prop.ligandName, prop.docPath, prop.kds[4].kd, prop.kds[4].kdStdDev];
					reportStrm.writeln(arrItem.join(","));
				}
				csvReportFile.close();
			} else {
				mnError("Unable to open file %1".arg(csvReportFile.name));
			}
		}
	}
};

if (this.MnUi && MnUi.scripts_binding) {
	MnUi.scripts_binding.cspImportPeaksFromFile = ImportCSPHandler.importPeakListFromFile;
	MnUi.scripts_binding.cspCreateFromTitrationFile = ImportCSPHandler.onCSPOpenTriggered;

	MnUi.scripts_binding.update = function (aUpdateObj) {
		"use strict";
		if (Application.binding) {
			aUpdateObj["cspImportPeaksFromFile"].enabled = Application.binding.currentResultId !== "";
		} else {
			Object.getOwnPropertyNames(aUpdateObj).forEach(function (aActionName) {
				aUpdateObj[aActionName].enabled = false;
			});
		}
	};
}

if (Application.engine === "dbg") {
ImportCSPHandler.test = function () {
	"use strict";
	var titrationFile = "C:/Users/isaac/tmp/ChemShiftPerturbation/Santi/titration_12cpds_200928-Small.txt",
		ligandsFile = "C:/Users/isaac/tmp/ChemShiftPerturbation/Santi/ligand_12cpds_200928-Small.txt",
		peaksFile = "C:/Users/isaac/tmp/ChemShiftPerturbation/Santi/peaklist_12cpds_200928.txt",
		hnd = new ImportCSPHandler(titrationFile, ligandsFile, peaksFile);


};
}
